import XLSX from 'xlsx';
import { Loading } from 'element-ui';

const excel = {
  /**
   * json转excel
   *
   * @param data 原始数据
   * @param filter 过滤条件
   * @param filename 文件名
   */
  export(data, filter, filename = new Date().getTime()) {
    // 数据处理
    let colHeader = [];
    Object.keys(filter).forEach((key) => {
      colHeader.push(filter[key]);
    });
    const list = data.map((item) => {
      let obj = {};
      Object.keys(filter).forEach((key) => {
        obj[filter[key]] = item[key] || '';
      });

      return obj;
    });
    // workbook属性
    const workbook = {
      SheetNames: ['Sheet1'],
      Sheets: {},
      Props: {},
    };
    workbook.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(list, { header: colHeader });
    // excel属性
    const options = {
      bookType: 'xlsx',
      bookSST: false,
      type: 'binary',
      showGridLines: true,
    };
    // 数据写入
    const binary = XLSX.write(workbook, options);
    // 保存文件
    const blob = this.binaryToBlob(binary);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename + '.xlsx';
    link.click();
  },
  binaryToBlob(stream) {
    let buffer = new Uint8Array(stream.length);
    for (let i = 0; i < stream.length; i++) {
      buffer[i] = stream.charCodeAt(i);
    }

    return new Blob([buffer]);
  },
  /**
   * 导入
   * @param file 文件对象
   * @param filter 过滤条件
   * @param message 提示信息
   * @returns Promise
   */
  import(file, filter, message = '正在解析Excel文件，请耐心等待……') {
    return new Promise((resolve, reject) => {
      const loading = Loading.service({
        lock: true,
        text: message,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      let reader = new FileReader();
      reader.onload = (e) => {
        const workbook = XLSX.read(e.target.result, { type: 'binary' });
        // 只取第一个sheet的数据
        const sheet = workbook.Sheets[workbook.SheetNames[0]];
        const data = XLSX.utils.sheet_to_json(sheet);
        const rst = data.map((item) => {
          const obj = {};
          Object.keys(filter).forEach((key) => {
            obj[key] = item[filter[key]] || null;
          });

          return obj;
        });

        loading.close();
        resolve(rst);
      };
      reader.onerror = (e) => {
        loading.close();
        reject(e);
      };
      reader.readAsBinaryString(file);
    });
  },
};

export default excel;
